package com.bqmart.tool.web.controller;

import com.bqmart.tool.web.form.User;
import com.bruce.tool.common.util.LogUtils;
import com.bruce.tool.common.util.string.JsonUtils;
import com.bruce.tool.web.filter.annotation.ForbidResubmit;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;

/**
 * 功能 :
 *
 * @author : Bruce(刘正航) 上午12:28 2018/1/2
 */
@Slf4j
@RestController
@RequestMapping("/")
public class WebController {

    @GetMapping(value = "/hello")
    public String hello(){
        return "Hello World";
    }

    @PostMapping(value = "/form")
    public String form(
            @RequestParam("name") String name,
            @RequestParam(value = "age",required = false) Integer age,
            @RequestParam("mail") String email ){

        User user = new User(name,age,email);

        return JsonUtils.objToStr(user);
    }

    @PostMapping(value = "/form/anno")
    public String form(
            @ModelAttribute("user") User user ){

        return JsonUtils.objToStr(user);
    }

    @PostMapping(value = "/json")
    public String json(HttpServletRequest request) throws IOException {

        InputStream in = request.getInputStream();

        Integer length = 0;
        byte[] buffer = new byte[4096];
        StringBuilder sb = new StringBuilder();
        while((length = in.read(buffer))>0){
            sb.append(new String(buffer,0,length));
        }

        LogUtils.info(log,sb.toString());

        LogUtils.info(log,JsonUtils.strToObj(sb.toString(),Map.class));

        return sb.toString();
    }

    @ForbidResubmit
    @PostMapping(value = "/json/anno")
    public User json(@RequestBody User user){
        System.out.println(1/0);
        return user;
    }

}
